<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="roleslist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="['dbbottom', i1 === 0 ? 'dbtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="['dbbottom', i2 === 0 ? 'dbtop' : '', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 通过循环渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="13">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre></pre>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="350px">
          <template v-slot="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(scope.row)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配权限按钮 -->
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
    >
      <el-tree
        show-checkbox
        :data="rightslist"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeref"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="roleinfo"
        :rules="editFormRules"
        ref="editRoleFormRef"
        label-width="80px"
        @close="editDialogClosed"
      >
        <!-- 修改用户内容主体区域 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleinfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleinfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 修改用户底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
          <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRoleDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <el-form
          :model="addForm"
          :rules="addRoleFormRules"
          ref="addForm"
          label-width="80px"
        >
          <!-- 添加用户内容主体区域 -->
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 添加用户底部按钮区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有角色的列表数据
      roleslist: [],
      //控制编辑角色对话框的显示隐藏
      editDialogVisible: false,
      //控制添加角色对话框的显示隐藏
      addRoleDialogVisible: false,
      // 控制分配权限对话框的显示隐藏
      setRightDialogVisible: false,
      // 所有权限列表
      rightslist: [],
      //树形控件的树形绑定对象
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      //默认选中的权限
      defkeys: [],
      //即将被分配权限的角色的ID
      roleid: '',
      //准备编辑的角色信息
      roleinfo: {},
      //添加角色的信息
      addForm:{
        roleName:'',
        roleDesc:''
      },
      //编辑角色规范
      editFormRules:{
        roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
          ],
        roleDesc: [
            { required: true, message: '请输入角色描述', trigger: 'blur' },
            { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
          ],
      },
      //添加角色规范
      addRoleFormRules:{
        roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
          ],
        roleDesc: [
            { required: true, message: '请输入角色描述', trigger: 'blur' },
            { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
          ],
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.console.error('获取角色列表失败')
      }
      this.roleslist = res.data
    },
    async removeRightById(row, id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return
      }
      const { data: res } = await this.$http.delete(
        'roles/' + row.id + '/rights/' + id
      )
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      row.children = res.data
      this.$message.success('删除成功')
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleid = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return
      this.rightslist = res.data
      this.getLeafKeys(role, this.defkeys)
      this.setRightDialogVisible = true
    },
    //通过递归的形式获取默认选定的三级权限的id,保存到defkeys中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 为角色分配权限
    async allotRights() {
      const key = [
        ...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys(),
      ]
      const idStr = key.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleid}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新权限失败')
      }
      this.getRolesList()
      this.$message.success('分配权限成功')
      this.setRightDialogVisible = false
    },
    //编辑按钮点击事件
    editRole(role) {
      this.roleinfo = role
      this.editDialogVisible = true
    },
    //监听修改用户对话框关闭后的重置事件
    editDialogClosed(){
      this.$refs.editRoleFormRef.resetFields()
    },
    //编辑用户的确认按钮事件
    saveRoleInfo(){
      this.$refs.editRoleFormRef.validate(async vaild=>{
        if(!vaild) return;
        //发起修改信息的数据请求
       const{data:res}=await this.$http.put('roles/' +this.roleinfo.id,{
          roleName:this.roleinfo.roleName,
          roleDesc:this.roleinfo.roleDesc
          });
          if (res.meta.status !== 200) {
          this.$message.error('编辑角色失败')
        }
        this.getRolesList();
        this.editDialogVisible = false;
        this.$message.success('编辑成功')
      })
    },
    //监听添加角色对话框的关闭事件
    addDialogClosed() {
      this.$refs.addForm.resetFields()
    },
    //添加角色点击按钮事件
    addRole(){
      this.$refs.addForm.validate(async (vaild) => {
        if (!vaild) return
        //发送添加用户网络请求
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        // 隐藏添加用户对话框
        this.addRoleDialogVisible = false
        // 重新获取用户数据
        this.getRolesList()
      })
    },
        //根据对应id删除用户
   async removeRoleById(id){
   const confirmResult= await  this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch( err => err )
        if(confirmResult !=='confirm') return;
      const{data:res}= await this.$http.delete('roles/'+id,id);
        if (res.meta.status !== 200) {
          this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.getRolesList();
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.dbtop {
  border-top: 1px solid #eee;
}
.dbbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}

</style>